package com.wayz.interceptor;

import com.wayz.exception.ExceptionCode;
import com.wayz.exception.WayzException;
import com.wayz.service.UserAdminService;
import com.wayz.util.CookieHelper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JSON鉴权拦截器类
 * 
 * @author yinjy
 *
 */
public class JsonAuthorityInterceptor extends HandlerInterceptorAdapter {

	/** 服务相关 */
	/** 鉴权代理 */
	@Reference(version = "1.0.0", check=false)
	private UserAdminService userAdminService = null;

	/** 常量相关 */
	/** 我的标识 */
	private static final String MYID = "myId";
	/** 登录令牌 */
	private static final String TOKEN = "token";

	/**
	 * 处理前调用
	 * 
	 * @param request HTTP请求
	 * @param response HTTP应答
	 * @param handler 处理器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取令牌
		String token = CookieHelper.getCookieValue(request.getCookies(), TOKEN);
		if (token == null) {
			throw new WayzException(ExceptionCode.TOKEN_INVALID, "令牌不存在");
		}

		// 获取标识
		Long myId = userAdminService.getMyId(token);

		if (myId == null) {
			throw new WayzException(ExceptionCode.TOKEN_INVALID, "令牌已失效");
		}
		// 设置标识
		request.getSession().setAttribute(MYID, myId);

		// 回调函数
		return super.preHandle(request, response, handler);
	}

}
